package com.base.common.interceptor;

import com.base.common.bean.ActionResult;
import com.base.common.json.JsonUtil;
import com.cjy.common.bean.OpAttributes;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;
import org.apache.struts2.StrutsStatics;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

import static com.base.GlobaConstants.ASYNCHRONOUS;


public class CheckUserInterceptor extends AbstractInterceptor {

	private static final long serialVersionUID = 1L;

	protected ActionResult actionResult;
	
	/**
	 * @param invocation
	 * @throws IOException
	 */
	public void getJsonResult(ActionInvocation invocation) throws IOException {
		HttpServletResponse httpServletResponse = (HttpServletResponse) invocation.getInvocationContext().get(StrutsStatics.HTTP_RESPONSE);
		PrintWriter printWriter = httpServletResponse.getWriter();
		printWriter.println(JsonUtil.dto2String(actionResult.getData()));
		printWriter.flush();
		printWriter.close();
	}

	@Override
	public String intercept(ActionInvocation invocation) throws Exception {
		
		System.out.println("-----------------------你好，你来到了拦截器----------------------------");
		
		System.out.println(invocation.getProxy().getMethod());
		
		HttpServletRequest httpServletRequest = (HttpServletRequest) invocation.getInvocationContext().get(StrutsStatics.HTTP_REQUEST);
		
//		System.out.println(httpServletRequest.getSession().getAttribute("code"));
		
//		httpServletRequest.getSession().setAttribute("code", 100);
		System.out.println(httpServletRequest.getCookies());
		System.out.println(invocation.getProxy().getMethod());
//		if(isNeedValidSession(invocation.getProxy().getMethod())){
		if (true){
			System.out.println("需要验证session");
			System.out.println("session非空判断：" + httpServletRequest.getSession());
//			if(httpServletRequest.getSession() != null && httpServletRequest.getSession().getAttribute("users") != null){
			if (true){
				System.out.println("进入方法--------");
				invocation.invoke();
			} else {
				actionResult = ActionResult.getActionResult(new OpAttributes().add("code", -1));
				// 设置json返回值
				getJsonResult(invocation);
			}
		} else {
			System.out.println("不需要session-------");
			invocation.invoke();
		}
		
		return ASYNCHRONOUS;
	}

	/**
	 * 验证是否需要验证session
	 * 
	 * @return
	 */
	public boolean isNeedValidSession(String methodName){
		System.out.println("判断是否需要验证session-------------");
		return !(methodName.equals("getLatestVersion") || methodName.equals("login")
				|| methodName.equals("registe") || methodName.equals("employeeLogin")
				|| methodName.equals("employeeRegiste") || methodName.equals("queryAll"));
	}
	
}
